//https://www.expressjs.com.cn/starter/basic-routing.html
// express 快速入门
const express = require("express");
const path = require("path");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const courseRouter = require("./routes/course");
const createError = require("http-errors");
const logger = require("morgan"); // 控制台log请求输出
const cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");

// const mongoose = require("mongoose");

// // 连接数据库（当前没有，一会去创建下，或者第一次调用会自动创建），返回值是promise
// mongoose
//   .connect("mongodb://localhost/testDB")
//   .then(() => console.log("数据库连接成功！！！"))
//   .catch((err) => console.log("无法连接数据库", err));

// const courseSchema = new mongoose.Schema({
//   name: String,
//   author: String,
//   tags: [String],
//   date: { type: Date, default: Date.now },
//   isPublic: Boolean,
// });
// // add api
// const Course = mongoose.model("add", courseSchema);

// async function createCouse() {
//   const course = new Course({
//     name: "react",
//     author: "杨大仙啥擦",
//     tags: ["js", "前端"],
//     isPublic: true,
//   });
//   let res = await course.save();
//   console.log(res, "res:");
// }

// // createCouse();

// // search api
// async function searchAll() {
//   const res = await Course.find({ author: "mac", isPublic: true })
//     .limit(1)
//     .sort({ name: 1 })
//     .select({ name: 1, author: 1 });
//   console.log(res);
// }
// // searchAll();

// async function query() {
//   let pageSize = 4;
//   let pageNumber = 2;
//   const res = await Course.find()
//     .skip((pageNumber - 1) * pageSize)
//     .limit(pageSize)
//     .sort({ name: 1 })
//     .select({ name: 1, author: 1 });
//   console.log(res);
// }
// query();
const app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

// midware
// app.use(express.static("public"));
app.use("/static", express.static(path.join(__dirname, "public")));
// 自定义中间件（顺序很重要，FIFU先写先调用）
const myLogger = (req, res, next) => {
  console.log("进入了一个请求，中间件拦截并记录日志");
  next();
};

app.use(myLogger);
app.use(logger("dev"));
app.use(express.json()); // json解析
app.use(express.urlencoded({ extended: false })); // form格式解析
app.use(cookieParser()); // cookie解析
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use("/api", indexRouter); // /路径会映射到index文件
app.use("/api/user", usersRouter); // /user路径会映射到users文件
app.use("/api/courses", courseRouter);

// catch 404 and forward to error handler 404需要单独处理
app.use(function (req, res, next) {
  next(createError(404));
});

function logErrors(err, req, res, next) {
  console.error(err.stack);
  next(err);
}

function clientErrorHandler(err, req, res, next) {
  if (req.xhr) {
    res.status(500).send({ error: "Something failed!" });
  } else {
    next(err);
  }
}

// error handler 默认错误处理，无法处理404
function errorHandler(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error", { error: err });
}

app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);

// const port = process.env.PORT || 3000;
// app.listen(port, () => {
//   console.log(`正在监听 ${port} 端口`);
// });
module.exports = app;
